/**
 * @file 工具函数
 * @author Iain
 * @creation 2021/11/27
 */

import Vue from "vue";
const vm = new Vue();

export function toast(msg) {
  vm.$u.toast(msg);
}

// 对Date的扩展，将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(H)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// 例子：
// (new Date()).format("yyyy-MM-dd HH:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).format("yyyy-M-d H:m:s.S")      ==> 2006-7-2 8:9:4.18
export function format(fmt) {
  //author: meizz
  var o = {
    "M+": this.getMonth() + 1, //月份
    "d+": this.getDate(), //日
    "h+": this.getHours(), //小时
    "m+": this.getMinutes(), //分
    "s+": this.getSeconds(), //秒
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
    S: this.getMilliseconds(), //毫秒
  };
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(
      RegExp.$1,
      (this.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt))
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
      );
  return fmt;
}

/**
 * @name 删除URL参数
 *
 * @param {string} url URL地址
 * @param {string} name 参数名
 * 如 delUrlParam(location.href,'tt')
 */
export function delUrlParam(url, name) {
  const urlArr = url.split("?");
  if (urlArr.length > 1 && urlArr[1].indexOf(name) > -1) {
    const query = urlArr[1];
    const obj = {};
    const arr = query.split("&");
    for (let i = 0; i < arr.length; i++) {
      arr[i] = arr[i].split("=");
      obj[arr[i][0]] = arr[i][1];
    }
    delete obj[name];
    const urlte =
      urlArr[0] +
      "?" +
      JSON.stringify(obj)
        // eslint-disable-next-line
        .replace(/[\"\{\}]/g, "")
        // eslint-disable-next-line
        .replace(/\:/g, "=")
        // eslint-disable-next-line
        .replace(/\,/g, "&");
    return urlte;
  } else {
    return url;
  }
}

/**
 * @name 对象深拷贝
 */
export function copy(obj, type = "json") {
  let robj = {};
  if (type === "json") robj = jsonCopy(obj);
  else robj = forinCopy(obj);
  return robj;
}

/**
 * @name 序列化-深拷贝
 */
export function jsonCopy(obj) {
  return JSON.parse(JSON.stringify(obj));
}

/**
 * @name  for-in-深拷贝对象
 */
export function forinCopy(obj) {
  const result = Array.isArray(obj) ? [] : {};
  for (const key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      if (typeof obj[key] === "object" && obj[key] !== null) {
        //递归复制
        result[key] = forinCopy(obj[key]);
      } else result[key] = obj[key];
    }
  }
  return result;
}

/**
 * @name 将地址参数转为对象
 */
export function fquery(url) {
  var reg_url = /^[^\?]+\?([\w\W]+)$/,
    reg_para = /([^&=]+)=([\w\W]*?)(&|$)/g, //g is very important
    arr_url = reg_url.exec(url),
    ret = {};
  if (arr_url && arr_url[1]) {
    var str_para = arr_url[1],
      result;
    while ((result = reg_para.exec(str_para)) != null) {
      ret[result[1]] = result[2];
    }
  }
  return ret;
}

/**
 * @name 数量 - 以万为单位显示
 */
export function fnum(num) {
  num = Number(num);
  if (num) {
    if (num >= 10000) {
      num = (num / 10000).toFixed(2) + "万";
    }
  } else num = 0;
  return num;
}

/**
 * @name 手机号格式验证
 */
export function checkPhone(phone) {
  const reg = /^1([358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$/;
  return reg.test(phone);
}

/**
 * @name 验证值是否为空
 */
export function checkValEmpty(str) {
  if (str) {
    if (typeof str === "object") {
      return Array.isArray(str)
        ? str.length <= 0
        : Object.keys(str).length <= 0;
    } else return false;
  } else return true;
}

/**
 * 节流函数 定时器方案
 * @param {Function} fn
 * @param {Number} delay
 */
export function throttle(fn, delay) {
  let valid = true;
  return function () {
    console.log(valid);
    if (!valid) {
      // 不触发
      return false;
    }
    // 执行函数并且在间隔期内把状态位设为无效
    valid = false;
    setTimeout(() => {
      console.log("执行方法");
      fn();
      valid = true;
    }, delay);
  };
}
/**
 * 节流函数 时间戳方案
 * @param {Function} fn
 * @param {Number} delay
 */
export function throttle2(fn, delay) {
  let last = 0;
  return function () {
    const now = Date.now();
    if (now - last >= delay) {
      // @ts-ignore
      // eslint-disable-next-line prefer-rest-params
      fn.apply(this, arguments);
      last = now;
    }
  };
}
/**
 * 防抖函数
 * @param {Function} fn
 * @param {Number} wait
 */
export function debounce(fn, wait) {
  let timer = null;
  return function () {
    console.log(timer);
    if (timer !== null) {
      clearTimeout(timer);
    }
    timer = setTimeout(fn, wait);
  };
}

export default {
  toast,
  format,
  delUrlParam,
  copy,
  jsonCopy,
  forinCopy,
  fquery,
  fnum,
  checkPhone,
  checkValEmpty,
  throttle,
  throttle2,
  debounce,
};
